package com.wuzihao.snake;

import java.util.LinkedList;

public class Snake {

    private LinkedList<Node> body = new LinkedList<>();
    //蛇的默认移动方向
    private Direction direction = Direction.LEFT;
    //蛇是否活着
    private boolean isLiving=true;

    public Snake(){
        initSnake();
    }

    public LinkedList<Node> getBody() {
        return body;
    }

    public void setBody(LinkedList<Node> body) {
        this.body = body;
    }

    private void initSnake(){
        this.body = new LinkedList<>();
        body.add(new Node(16,20));
        body.add(new Node(17,20));
        body.add(new Node(18,20));
        body.add(new Node(19,20));
        body.add(new Node(20,20));
        body.add(new Node(21,20));

    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public void move() {
        if(isLiving){
            Node head = body.getFirst();
            switch (direction){
                case UP:
                    //在蛇头的上边添加一个节点
                    body.addFirst(new Node(head.getX(),head.getY()-1));
                    break;
                case DOWN:
                    body.addFirst(new Node(head.getX(),head.getY()+1));
                    break;
                case LEFT:
                    body.addFirst(new Node(head.getX()-1,head.getY()));
                    break;
                case RIGHT:
                    body.addFirst(new Node(head.getX()+1,head.getY()));
                    break;
            }
            //删除最后的节点
            body.removeLast();

            //判断蛇是否撞墙
            head=body.getFirst();
            if(head.getX()<0||head.getY()<0||head.getX()>=40||head.getY()>=40){
                isLiving=false;
            }

            //判断蛇是否碰到自己的身体
            for (int i = 1; i < body.size(); i++) {
                Node node = body.get(i);
                if(head.getX()==node.getX()&&head.getY()==node.getY()){
                    isLiving=false;
                }
            }
        }
    }

    public void eat(Node food) {
        //获取蛇头
        Node head = body.getFirst();
        switch (direction){
            case UP:
                //在蛇头的上边添加一个节点
                body.addFirst(new Node(head.getX(),head.getY()-1));
                break;
            case DOWN:
                body.addFirst(new Node(head.getX(),head.getY()+1));
                break;
            case LEFT:
                body.addFirst(new Node(head.getX()-1,head.getY()));
                break;
            case RIGHT:
                body.addFirst(new Node(head.getX()+1,head.getY()));
                break;
        }
    }
}
